package cn.toolck.controller;

import cn.toolck.config.DataSource;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.json.JsonMapper;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Collections;
import java.util.Map;

@Controller
public class OrderController {
    @Autowired
    public RabbitTemplate rabbitTemplate;

    @GetMapping("/createOrder/{orderId}")
    @ResponseBody
    public Boolean createOrder(@PathVariable String orderId) throws Exception {
        Map<String, Object> messageObject = Collections.singletonMap("orderId", orderId);
        ObjectMapper objectMapper = new ObjectMapper();
        final String messageStr = objectMapper.writeValueAsString(messageObject);
        MessageProperties properties = new MessageProperties();
        properties.setContentEncoding(StandardCharsets.UTF_8.name());
        Message message = MessageBuilder.withBody(messageStr.getBytes(StandardCharsets.UTF_8)).andProperties(properties).build();
        rabbitTemplate.convertAndSend("ex.toolck.pay", "toolck.pay", message);
        DataSource.orderMap.put(orderId, messageObject);
        return true;
    }

    @GetMapping("/pay/{orderId}")
    @ResponseBody
    public Boolean pay(@PathVariable String orderId) {
        Map<String, Object> payObject = Collections.singletonMap("orderId", orderId);
        // 如果在数据源中存在订单（表示状态为未完成）则可以支付并可以支付完成
        if (DataSource.orderMap.containsKey(orderId)) {
            DataSource.payMap.put(orderId, payObject);
            return true;
        }
        return false;
    }
}
